package me.zhengjie.modules.account.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.account.domain.AccountAc08;
import me.zhengjie.modules.account.domain.dto.AccountAc08QueryCriteria;
import me.zhengjie.modules.account.factory.entity.BaseUnitApprove;
import me.zhengjie.modules.account.factory.vo.CheckPersonFees;
import me.zhengjie.modules.account.factory.vo.CollectBillBank;
import me.zhengjie.modules.account.mapper.AccountAa03Mapper;
import me.zhengjie.modules.account.mapper.AccountAc08Mapper;
import me.zhengjie.modules.account.mapper.AccountAc43Mapper;
import me.zhengjie.modules.account.service.AccountAc08Service;
import me.zhengjie.modules.account.service.AccountAc43Service;
import me.zhengjie.modules.basic.domain.BasicAe03;
import me.zhengjie.modules.basic.mapper.BasicAe03Mapper;
import me.zhengjie.modules.sequence.domain.Sequence;
import me.zhengjie.modules.sequence.service.SequenceService;
import me.zhengjie.tool.ListUtil;
import me.zhengjie.tool.MyMap;
import me.zhengjie.tool.NPETool;
import me.zhengjie.tool.ValidateUtil;
import me.zhengjie.utils.PageResult;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.vo.Constant;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.swagger2.mappers.ModelMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Transactional
public class AccountAc43ServiceImpl extends ServiceImpl<AccountAc43Mapper, AccountAc08> implements AccountAc43Service {

    private final AccountAc43Mapper accountAc43Mapper;
    private final AccountAc08Mapper accountAc08Mapper;
    private final BasicAe03Mapper basicAe03Mapper;
    private final SequenceService sequenceService;


    @Override
    public PageResult<AccountAc08> queryAll(Map param, Page<Object> page) {
        return PageUtil.toPage(accountAc43Mapper.selectAc08(param, page));
    }

    @Override
    public List<AccountAc08> queryAll(AccountAc08QueryCriteria criteria) {
        return null;
    }

    @Override
    public void download(List<AccountAc08> all, HttpServletResponse response) throws IOException {

    }

    @Override
    public Map save(MyMap businessParam) throws Exception {
        if (ValidateUtil.isEmpty(businessParam.get("businessList"))) {
            throw new RuntimeException("单位职工欠费核销和单位职工退退款参数为空");
        }
        List<Map> paramList = (List<Map>) JSON.parse(businessParam.get("businessList").toString());//已到账List
        List<MyMap> businessList = ListUtil.mapList2MyMapList(paramList);
        businessParam.put("bae944", Constant.BAE944_1_S);
        // 核定结果单位核定结果信息
        List<BaseUnitApprove> checkApproves = new ArrayList<>();

        String aaz615 = sequenceService.nextSequence(new Sequence("aaz615"));
        String aaz616 = sequenceService.nextSequence(new Sequence("aaz616"));
        String aaz627 = sequenceService.nextSequence(new Sequence("aaz627"));
        String aaz650 = sequenceService.nextSequence(new Sequence("aaz650"));
        String aaz625 = sequenceService.nextSequence(new Sequence("aaz625"));
        String aae066 = sequenceService.nextSequence(new Sequence("aae066"));

        String aab001 = businessParam.getAsString("aab001");
        Map<String, List<MyMap>> registerPersons = businessList.stream().collect(Collectors.groupingBy(m -> m.getAsString("aae140")));
        registerPersons.forEach((aae140, persons) -> {
            MyMap myMap = new MyMap();
            myMap.putAll(businessParam);
            myMap.put("aae763", businessParam.getAsString("aae763"));
            myMap.put("aae822", businessParam.getAsString("aae822"));

            myMap.put("aaz615", aaz615);
            myMap.put("aaz616", aaz616);
            myMap.put("aaz627", aaz627);
            myMap.put("aaz650", aaz650);
            myMap.put("aaz625", aaz625);
            myMap.put("aae066", aae066);
            myMap.put("aae140", aae140);
            myMap.put("registerPerson", persons);
            BaseUnitApprove checkApprove = new BaseUnitApprove(sequenceService);
            checkApprove.init(myMap);
            //生成退费明细
            checkApprove.initCheckDetailApprove();
            checkApproves.add(checkApprove);
        });

        NPETool.isEmptyThrowException(checkApproves, "人员退款结果");
        businessParam.put("aae768", businessParam.get("aae013"));

        // 保存ac08
        for (BaseUnitApprove newCheckApprove : checkApproves) {
            accountAc08Mapper.batchInsertAc08(newCheckApprove.getPersonFees());
        }

        // 出单
        if (Constant.BAE944_1_S.equals(businessParam.get("bae944"))) {
            businessParam.put("aab001", aab001);
            NPETool.isEmptyThrowException(businessParam.get("aab001"), "单位编号");
            //银行信息
            Map queryMap = Maps.newHashMap();
            queryMap.put("aaz010", businessParam.get("aab001"));
            queryMap.put("aaa028", Constant.AAA028_11_DW);

            List<BasicAe03> ae03s = basicAe03Mapper.getAe03List(queryMap);
            if (ValidateUtil.isEmpty(ae03s)) {
                throw new RuntimeException("未查询到单位的银行信息，请先维护");
            }
            Map<String, List<BasicAe03>> ae03Maps = ae03s.stream().collect(Collectors.groupingBy(ae03 -> ae03.getAae140()));
            List<Map> list = new ArrayList<>();
            for (BaseUnitApprove newCheckApprove : checkApproves) {
                //退费数据才能进行发单操作
                List<CheckPersonFees> reList = newCheckApprove.getPersonFees().stream().filter(checkUnitFees -> checkUnitFees.getAae792().equals(Constant.AAE792_05_TF)).collect(Collectors.toList());
                for (CheckPersonFees checkCollect : reList) {
                    Map cmap = ValidateUtil.objectToMap(checkCollect);
                    if (ValidateUtil.isEmpty(ae03Maps.get(cmap.get("aae140")))) {
                        throw new RuntimeException("未获取到单位【" + cmap.get("aae140") + "】的银行信息");
                    }
                    BasicAe03 basicAe03 = ae03Maps.get(cmap.get("aae140")).get(0);
                    MyMap myMap = JSONObject.parseObject(JSONObject.toJSONString(basicAe03),MyMap.class);
                    CollectBillBank collectBillBank =
                            new CollectBillBank(myMap);
                    cmap.putAll(JSONObject.parseObject(JSONObject.toJSONString(collectBillBank),Map.class));
                    cmap.put("aab001", aab001);
                    list.add(cmap);
                }
            }

            //组装单据信息
            BaseUnitApprove checkApprove = new BaseUnitApprove(sequenceService);
            checkApprove.setCollectBillBankList(list);
            checkApprove.createFinancialDocuments(checkApproves);

            // 插入ad01
            List<Map> documentList = checkApprove.getDocumentList();
            accountAc08Mapper.batchInsertAd01(documentList);

        }

        return null;
    }
}
